package cn.reinforce.util.aliyun;

import cn.reinforce.util.aliyun.exception.AliyunException;
import cn.reinforce.util.aliyun.model.ErrorResponse;
import cn.reinforce.util.aliyun.model.ocr.OcrRequest;
import cn.reinforce.util.aliyun.model.ocr.OcrResponse;
import cn.reinforce.util.http.HttpClientUtil;
import cn.reinforce.util.http.model.HttpResult;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import org.apache.commons.collections4.map.HashedMap;

import java.io.UnsupportedEncodingException;
import java.util.Map;

/**
 * @author 幻幻Fate
 * @date 2019/1/23
 * @since
 */
public class AliyunOcrUtil {

    public static OcrResponse ocr(String imageUrl, String appCode) throws UnsupportedEncodingException {
        String url = "https://ocrapi-document.taobao.com/ocrservice/document";
        Map<String, String> headers = new HashedMap();
        headers.put("Authorization", "APPCODE " + appCode);

        Gson gson = new GsonBuilder().create();

        OcrRequest ocrRequest = new OcrRequest();
        ocrRequest.setUrl(imageUrl);

        HttpResult result = HttpClientUtil.postByEntity(url, gson.toJson(ocrRequest), headers);

        OcrResponse ocrResponse = gson.fromJson(result.getResult(), OcrResponse.class);

        if(ocrResponse == null){
            ErrorResponse errorResponse = gson.fromJson(result.getResult(), ErrorResponse.class);
            throw new AliyunException(errorResponse.getErrorMsg());
        }

        return gson.fromJson(result.getResult(), OcrResponse.class);
    }
}
